
import { _decorator, Component, Node } from 'cc';
import { TileMapManager } from '../Tile/TileMapManager';
import { createUINode } from '../Utils';
import levels, { ILevel } from '../../Levels'
import  DataManager  from '../../Runtime/DataManager';
import { TILE_HEIGHT, TILE_WIDTH } from '../Tile/TileManager';
import EventManager from '../../Runtime/EventManager';
import { EVENT_ENUM } from '../../Enums';
import { PlayerManager } from '../Player/PlayerManager';
import { WoodenSkeletonManager } from '../WoodenSkeleton/WoodenSkeletonManager';
const { ccclass, property } = _decorator;

@ccclass('BattleManager')
export class BattleManager extends Component {
  // 当前关卡
  level:ILevel
  // 游戏舞台
  stage:Node

  onLoad() {
    // 绑定
    EventManager.Instance.on(EVENT_ENUM.NEXT_LEVEL, this.nextLevel, this)
  }
  onDestroy() {
    EventManager.Instance.off(EVENT_ENUM.NEXT_LEVEL, this.nextLevel)
  }
  start () {
    // 生成舞台
    this.generateStage()
    // 初始化地图
    this.initLevel()
  }

  // 初始化关卡
  initLevel() {
    // 获取当前关卡地图信息
    const level = levels[`level${DataManager.Instance.levelIndex}`]
    if(level) {
      this.clearLevel()
      this.level = level
      // 将地图信息存储到数据中心
      DataManager.Instance.mapInfo = this.level.mapInfo
      DataManager.Instance.mapRowCount = this.level.mapInfo.length || 0
      DataManager.Instance.mapColumnCount = this.level.mapInfo[0].length || 0

      // 绘制地图
      this.generateTileMap()

      // 生成骷髅
      this.generateEnemies()
      // 生成角色
      this.generatePlayer()
    }
  }

  // 下一关
  nextLevel() {
    DataManager.Instance.levelIndex++
    this.initLevel()
  }
  // 清空关卡内容
  clearLevel() {
    this.stage.destroyAllChildren()
    DataManager.Instance.reset()
  }

  // 生成舞台
  generateStage() {
    this.stage = createUINode()
    this.stage.setParent(this.node)
  }

  // 生成地图
  async generateTileMap() {
    const tileMap = createUINode()
    tileMap.setParent(this.stage)

    const tileMapManager =  tileMap.addComponent(TileMapManager)
    await tileMapManager.init()

    // 适配屏幕
    this.adaptPos()
  }

  // 生成玩家
  async generatePlayer() {
    const player = createUINode()
    player.setParent(this.stage)

    const playerManager =  player.addComponent(PlayerManager)
    await playerManager.init()
    DataManager.Instance.player = playerManager
    EventManager.Instance.emit(EVENT_ENUM.PLAYER_BORN)
  }

  // 生成敌人
  async generateEnemies() {
    const enemy = createUINode()
    enemy.setParent(this.stage)

    const woodenSkeletonManager =  enemy.addComponent(WoodenSkeletonManager)
    await woodenSkeletonManager.init()
    DataManager.Instance.enemis.push(woodenSkeletonManager)
  }
  // 适配屏幕
  adaptPos() {
    // 地图场景向左偏移半个地图
    const { mapRowCount, mapColumnCount} = DataManager.Instance
    const disX = (TILE_WIDTH * mapRowCount) / 2
    const disY = (TILE_HEIGHT * mapColumnCount) / 2
    this.stage.setPosition(-disX, disY+80)
  }
}
